#include <stdio.h>
#include <stdlib.h>
#include <string.h> // For memset
#include "ReaderWriterUtilities.h"

//初始化ReaderWriterManager_t结构
void initReaderWriterManager(ReaderWriterManager_t *rwMgr) {
    // Initialize semaphores
    // sem_init(sem_t *sem, int pshared, unsigned int value);
    // pshared = 0 for thread sharing within a process
    if (sem_init(&rwMgr->rw_mutex, 0, 1) != 0) { // [Source 3, 35]
        perror("rw_mutex sem_init failed");
        exit(EXIT_FAILURE);
    }
    if (sem_init(&rwMgr->mutex, 0, 1) != 0) {
        perror("mutex sem_init failed");
        exit(EXIT_FAILURE);
    }

    // Initialize other members
    rwMgr->read_count = 0;
    memset(rwMgr->buffer, 0, BUFFER_SIZE); // Clear the buffer
    rwMgr->buffer_len = 0; // Assuming we track length
    rwMgr->exit_flag = 0;
}

// 分配内存并调用初始化函数
ReaderWriterManager_t *createReaderWriterManager() {
    ReaderWriterManager_t *rwMgr =
        (ReaderWriterManager_t *)malloc(sizeof(ReaderWriterManager_t)); // [Source 5, 37] similar allocation

    if (rwMgr == NULL) {
        perror("Failed to allocate memory for ReaderWriterManager");
        return NULL;
    }
    initReaderWriterManager(rwMgr);
    return rwMgr;
}

// 初始化线程参数结构体
void initThreadStruct(ThreadStruct_t *threadStruct, ReaderWriterManager_t *rwMgr, int threadIdx) {
    threadStruct->rwMgr = rwMgr;
    threadStruct->threadIdx = threadIdx;
    // tid is set by pthread_create
}

// --- Semaphore Wrappers (Copied/Adapted from ProducerConsumerUtilities.c) ---

// Wrapper for sem_wait with error checking
void semWait(sem_t *sem) {
    int ret = sem_wait(sem); // 将wait信号量减1
    if (ret < 0) { // [Source 20, 52]
        perror("sem_wait failed!");
        // In a real application, might handle differently than exit
        exit(EXIT_FAILURE);
    }
}

// Wrapper for sem_post with error checking
void semSignal(sem_t *sem) {
    int ret = sem_post(sem); // 将Signal信号量加1
    if (ret < 0) { // [Source 20, 52]
        perror("sem_post failed!");
        exit(EXIT_FAILURE);
    }
}

// Wrapper for sem_destroy with error checking
void semDestroy(sem_t *sem) {
    int ret = sem_destroy(sem); // 用于销毁一个通过初始化的未命名信号量
    if (ret < 0) { // [Source 20, 53]
        perror("sem_destroy failed");
        // Not exiting here, as cleanup might continue
    }
}
